package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 
 * date:2022/9/17 14:01
 * 描述：
 **/
@Service
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Override
    public String createAliPay(Long orderId) {
        //  根据订单Id 获取订单对象
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  保存交易记录.
        this.paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        //  判断订单状态：
        if ("CLOSED".equals(orderInfo.getOrderStatus()) || "PAID".equals(orderInfo.getOrderStatus())){
            return "订单已关闭或已支付!";
        }

        //  如果支付宝与微信只能二选一 ： 借助redis setnx 命令！
        //  支付宝与微信可以同时支付：    退款接口！

        //  AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipay.com/gateway.do" , APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);  //获得初始化的AlipayClient
          AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
//        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        //  设置同步回调  http://api.gmall.com/api/payment/alipay/callback/return
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //  设置异步回调  http://rjsh38.natappfree.cc/api/payment/alipay/callback/notify
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url); //在公共参数中设置回跳和通知地址

        //  第一种方式：
        JSONObject jsonObject = new JSONObject();
        //  商户订单号
        jsonObject.put("out_trade_no",orderInfo.getOutTradeNo());
        jsonObject.put("total_amount",0.01);
        jsonObject.put("subject",orderInfo.getTradeBody());
        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY"); // 电脑网站
//        jsonObject.put("product_code", "QUICK_WAP_WAY"); // 手机网站
        //  10m以后 设置二维码的过期时间：绝对时间：yyyy-MM-dd HH:mm:ss
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  时间计算：
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,10);
        jsonObject.put("time_expire",simpleDateFormat.format(calendar.getTime()));
        //  赋值操作
        alipayRequest.setBizContent(jsonObject.toJSONString());
        //  第二种方式: 可以设置map

        String form= "" ;
        try  {
            //  form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        //  返回数据
        return form;
    }

    @Override
    public Boolean refund(Long orderId) {
        //  根据orderId 获取订单
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        //  添加状态判断
        if ("CLOSED".equals(orderInfo.getOrderStatus())){
            return false;
        }
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo()); // 必须去paymentInfo 获取！
        //  bizContent.put("trade_no", "2021081722001419121412730660"); // 必须去paymentInfo 获取！
        bizContent.put("refund_amount", 0.01);  //  退款金额
        bizContent.put("refund_reason", "不好用");  //  退款原因
        //  bizContent.put("out_request_no", "HZ01RF001"); // 部分退款需要使用.


        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            //            if (response.getFundChange().equals("Y")) {
            //
            //            }
            //  修改交易状态. paymentInfo;
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
            paymentInfo.setUpdateTime(new Date());

            //  设置更新的条件：
            //            UpdateWrapper<PaymentInfo> paymentInfoUpdateWrapper = new UpdateWrapper<>();
            //            paymentInfoUpdateWrapper.eq("out_trade_no",orderInfo.getOutTradeNo());
            //            paymentInfoUpdateWrapper.eq("payment_type",PaymentType.ALIPAY.name());
            //            paymentInfoMapper.update(paymentInfo,paymentInfoUpdateWrapper);
            this.paymentService.updatePaymentInfoStatus
                    (orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name(),paymentInfo);
            //  orderInfo --- 状态. 1.  远程调用更新  2. 异步发送消息！

            System.out.println("调用成功");
            //  表示退款成功.
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean closePay(Long orderId) {
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean checkPayment(Long orderId) {
        //  根据orderId 获取 orderInfo 对象
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        //bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            //  可以获取到交易状态 trade_status 判断这个用户是否支付成功！
            System.out.println("交易状态："+response.getTradeStatus());
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }
}